<template>
  <Financial
    title="收付款管理"
    add-btn-text="新增收付款单"
    :columns="columns"
    :get-page-url="Api.paymentPage"
    :cud-url="Api.payment"
    create-title="新增收付款单"
    update-title="编辑收付款单"
    delete-message="确认删除该收付款单吗？"
    :model="model"
    :model-form-setting="modelFormSetting"
    review-api-key="paymentReview"
    nullify-api-key="paymentNullify"
    :detail-modal-options="detailModalOptions"
    @before-update-model="beforeUpdateModel"
    @before-ok="beforeOk"
    @show-detail="showDetail"
  >
    <template #detailCenter>
      <div class="mt-4 text-center">
        <a-image
          :src="detailModalOptions.data.voucherUrl"
          :height="400"
          class="!h-full !w-auto"
          :fallback="DEFAULT_IMG_BASE64_STR"
        ></a-image>
      </div>
    </template>
    <a-modal
      v-model:visible="selInvoiceVisible"
      :title="'选择发票'"
      :width="800"
      :body-style="{ padding: 0 }"
      @ok="handleInvoice"
    >
      <TableSelect
        ref="selInvoiceIns"
        v-model:value="invoiceIds"
        search-placeholder="搜索发票号码"
        search-key="keywords"
        :columns="invoiceColumns"
        :get-page-url="Api.invoicePage"
        :field-names="{ value: 'id', label: 'invoiceNum' }"
        single-select
      >
        <template #bodyCell="{ column, record }">
          <div v-if="column.dataIndex === 'invoiceUrl'">
            <a-image :fallback="DEFAULT_IMG_BASE64_STR" :src="record.invoiceUrl" :width="100" />
          </div>
          <FitTitleCell v-else :record="record" :column="column" />
        </template>
      </TableSelect>
    </a-modal>
  </Financial>
</template>
<script setup lang="ts">
import { h, ref } from "vue";
import Financial from "/@/views/common/Financial/Financial.vue";
import { TableColumnProps, message } from "ant-design-vue";
import { Api } from "/@/api/main/financial";
import { DetailModalOptions, FinancialItem, InvoiceType, PayOpType, PayRecMethod } from "/@/api/main/financial/models";
import { CURDAction, CURDModalEvent, FormItemComponentType, FormItemData } from "/@/components/CURDDialog/models";
import { enumToOptions, getLabelByValueFromEnum, handleDateRowRender } from "/@/utils/common";
import { getSupplierList } from "/@/api/main/pis";
import dayjs from "dayjs";
import { ReceiptStatus } from "/@/api/main/pis/models";
import { DEFAULT_IMG_BASE64_STR } from "/@/utils/file";
import { useInvoice } from "./useInvoice";
import SelectInput from "/@/components/common/SelectInput.vue";
import { usePayment } from "./usePayment";

const e = usePayment();
const columns = ref<TableColumnProps<FinancialItem>[]>(e.columns);

const model = ref<Partial<FinancialItem>>({
  opType: PayOpType.collect,
  _payRecDate: null,
  settlementOrderNo: "",
  supplierId: null,
  invoiceNum: "",
  payRecAmount: null,
  payRecMethod: 0,
  voucherNum: "",
  voucherUrl: "",
  remark: "",
});

const modelFormSetting = ref<FormItemData<Partial<FinancialItem>>[]>([
  {
    key: "opType",
    type: FormItemComponentType.SELECT,
    props: {
      options: enumToOptions(PayOpType, "payOpType"),
    },
    required: true,
  },
  {
    key: "_payRecDate",
    type: FormItemComponentType.DATEPICKER,
    label: "收付款日期",
    required: true,
    props: {
      valueFormat: null,
    },
  },
  {
    key: "settlementOrderNo",
  },
  {
    key: "supplierId",
    label: "供应商",
    type: FormItemComponentType.SELECT,
    props: {
      options: [],
    },
    async getData() {
      const data = await getSupplierList();
      return data
        ? data.map((item) => ({
            label: item.name,
            value: item.id,
            key: item.id,
          }))
        : [];
    },
    required: true,
  },
  {
    key: "invoiceNum",
    label: "发票号码",
    customComponent: h(SelectInput, {
      onClick() {
        selInvoiceVisible.value = true;
      },
    }),
  },
  {
    key: "payRecAmount",
    type: FormItemComponentType.NUMBER,
  },
  {
    key: "payRecMethod",
    type: FormItemComponentType.SELECT,
    props: {
      options: [{ label: "银行转账", value: 0 }],
    },
  },
  {
    key: "voucherNum",
  },
  {
    key: "voucherUrl",
    label: "收付款单图片",
    type: FormItemComponentType.IMGUPLOAD,
  },
  {
    key: "remark",
    label: "备注",
    type: FormItemComponentType.TEXTAREA,
  },
]);

function beforeUpdateModel(record: FinancialItem) {
  record._payRecDate = dayjs(record.payRecDate);
}

function beforeOk({ action, model }: CURDModalEvent<Partial<FinancialItem>>) {
  if (model) {
    model.payRecDate = model._payRecDate?.valueOf() as number;
    delete model._payRecDate;
    if (action === CURDAction.CREATE) {
      model.status = ReceiptStatus.waiting;
    }
  }
}
/**
 *
 */
const detailModalOptions = ref<DetailModalOptions>({
  title: "收付款单详情",
  triggerKeys: ["orderNo"],
  desKeys: [
    {
      key: "opType",
      customRender(value) {
        return value === 0 ? "付款单" : "收款单";
      },
    },
    "orderNo",
    "settlementOrderNo",
    "supplierName",
    "invoiceNum",
    { key: "payRecDate", isDate: true },
    "payRecAmount",
    { key: "payRecMethod", enumInfo: { enumData: PayRecMethod, localKey: "payRecMethod" } },
    "voucherNum",
  ],
  loading: false,
  data: {},
});
function showDetail(record: FinancialItem) {
  detailModalOptions.value.data = record;
}
/**
 *
 */
const selInvoiceVisible = ref(false);
const invoiceIds = ref<number[]>([]);
const { columns: invoiceColumns } = useInvoice(["oper"]);
const selInvoiceIns = ref();
function handleInvoice() {
  if (invoiceIds.value.length === 0) {
    return message.info("请选择发票");
  }
  if (selInvoiceIns.value) {
    const items = selInvoiceIns.value.getSelecedItems() as FinancialItem[];
    model.value.invoiceNum = items[0].invoiceNum;
    model.value.invoiceId = items[0].id;
  }
  selInvoiceVisible.value = false;
}
</script>
